// 给定一个m*n的二维矩阵，matrix，按照顺时针旋转的顺序，返回矩阵中的所有元素

// 思路：定义好边界指针 top，right， bottom， left，按照顺时针遍历且更新指针并在指针更新后判断是否需要中止遍历
// 时间复杂度为Om*n，m和n分别为二维矩阵的行和列数
// 空间复杂度为Om*n

function spiralOrder(matrix) {
    let m = matrix.length - 1
    let n = matrix[0].length - 1
    let top = 0
    let bottom = m
    let left = 0
    let right = n
    let ans = []
    while (true) {
        for (let i = left; i <= right; i++) {
            ans.push(matrix[top][i])
        }
        top++
        if (top > bottom) {
            break
        }
        for (let i = top; i <= bottom; i++) {
            ans.push(matrix[i][right])            
        }
        right--
        if (right < left) {
            break
        }
        for (let i = right; i >= left; i--) {
            ans.push(matrix[bottom][i])
        }
        bottom--
        if (bottom < top) {
            break
        }
        for (let i = bottom; i >= top; i--) {
            ans.push(matrix[i][left])            
        }
        left++
        if (left > right) {
            break
        }
    }
    return ans
}

let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
console.log(spiralOrder(matrix));